package com.hry.store.controller;

import com.hry.store.common.Const;
import com.hry.store.common.ServerResponse;
import com.hry.store.pojo.Province;
import com.hry.store.pojo.Shipping;
import com.hry.store.pojo.User;
import com.hry.store.service.ProvinceService;
import com.hry.store.service.ShippingService;
import com.hry.store.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ShippingService shippingService;
    @Autowired
    private ProvinceService provinceService;

    /***
     * 跳转到注册页面
     * @return
     */
    @RequestMapping("user/page/register")
    public String pageUser() {
        return "register";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping("user/page/login")
    public String pageLogin(HttpServletRequest request, HttpServletResponse response) {
        // 获取上一个路径
        String loginBackUrl=request.getHeader("Referer").toString();
        if (loginBackUrl.equals("")){
            loginBackUrl = "/page/index";
        }
        Cookie cookie = new Cookie("loginBackUrl", loginBackUrl);
        cookie.setMaxAge(30*24*60*60);   //存活期为一个月 30*24*60*60
        cookie.setPath("/");
        response.addCookie(cookie);
        return "login";
    }

    /**
     * 用户注册，密码进行md5加密
     */
    @RequestMapping("user/register")
    public String userRegister(HttpServletRequest request) {
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        String phone = request.getParameter("phone").trim();
        String email = request.getParameter("email").trim();
        userService.register(username, password, phone, email);
        // 跳转到提示用户邮箱激活邮件页面
        return "提示";
    }

    /**
     * 校验邮箱是否存在
     */
    @RequestMapping("user/verifyEmail")
    @ResponseBody
    public Boolean verifyEmail(@RequestParam(value = "checkEmail") String checkEmail) {
        Boolean result = userService.checkEmail(checkEmail);
        return result;
    }

    /**
     * 通过邮件激活用户
     */
    @RequestMapping("user/activate")
    public String userActivate(@RequestParam("email") String email, @RequestParam("key") String key) {
        boolean result = userService.activate(email, key);
        if (result) {
            // 激活成功
            return "index";
        }
        // 激活失败
        return "login";
    }

    /**
     * 用户登录
     */
    @RequestMapping("user/login")
    @ResponseBody
    public ServerResponse userLogin(HttpServletRequest request) throws Exception {
        String loginBackUrl = "";
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        int verifyCode = Integer.parseInt(request.getParameter("yanzhengma"));
        boolean result = userService.login(email, password, verifyCode, request);
        User user = userService.getUserInfo(email);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie: cookies) {
            if ("loginBackUrl".equals(cookie.getName())) {
                loginBackUrl =cookie.getValue();
            }
        }
        if (result) {
            // 登录成功
            request.getSession(true).setAttribute(Const.CURRENT_USER, user);
            return ServerResponse.createBySuccess(loginBackUrl);
        }
        return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "登录失败");
    }

    /**
     * 注销用户
     */
    @RequestMapping("user/exit")
    public String userExit(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/user/login";
    }

    /**
     * 用户详情页面
     */
    @RequestMapping("user/selfInfo")
    public String selfInfoPage(HttpServletRequest request) {
        User user1 = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        User user = userService.getUserInfo(user1.getUserEmail());
        request.getSession(true).setAttribute(Const.CURRENT_USER, user);
        return "self_info";
    }

    /**
     * 收货地址页面
     */
    @RequestMapping("user/address")
    public String userAddress(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "login";
        }
        // 查询地址
        List<Shipping> shippings = shippingService.findShippingByEmail(user.getUserEmail());
        if (!CollectionUtils.isEmpty(shippings)) {
            modelMap.put("shippings", shippings);
        }
        // 查询所有省份
        List<Province> provinceList = provinceService.getAll();
        if (!CollectionUtils.isEmpty(provinceList)) {
            modelMap.put("provinceList", provinceList);
        }
        return "address";
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("user/updateUserInfo")
    @ResponseBody
    public ServerResponse updateUserInfo(@RequestParam("name") String name, @RequestParam("email") String email, @RequestParam("phone") Long phone,
                                         @RequestParam("sign") String sign,@RequestParam("favorite") String favorite, HttpServletRequest request) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);

        int resultCount = userService.updateUser(user.getUserId(), name, email, phone, sign, favorite);
        if (resultCount > 0) {
            return ServerResponse.createBySuccess("更新成功", Const.SUCCESS_CODE);
        }
        return ServerResponse.createByErrorCodeMessage(Const.ERROR_CODE, "更新失败");

    }


}
